<template>
  <div class="container">
    <!-- 面包屑导航 -->
   <breadcrumb-top :breadcrumbConfig="dataList"></breadcrumb-top>
    <!-- 面包屑导航 -->
    <!-- 查询 -->
    <div class="content">
      <h2>商品列表</h2>
      <h3>数据筛选</h3>
      <div>
        <el-form :inline="true" :model="searchForm" ref="searchForm" class="search-form" size="small">
          <el-form-item label="商品名称" prop="name">
            <el-input
                v-model="searchForm.name"
                placeholder="请输入商品名称"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="商品编号" prop="goodsNo">
            <el-input
                v-model="searchForm.goodsNo"
                placeholder="请输入商品编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品类目" prop="categoryId">
            <el-cascader
                :options="categoryList"
                v-model="searchForm.categoryId"
                :props="{ checkStrictly: true }"
                @change="onChangeCategory"
                filterable
                clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="商品类型" prop="goodsType">
            <el-select
                v-model="searchForm.goodsType"
                placeholder="请选择商品类型"
                filterable
                clearable
            >
              <el-option
                  v-for="item in dictionaries.goods_type"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="品牌" prop="brandId">
            <el-select
                v-model="searchForm.brandId"
                placeholder="请选择品牌"
                filterable
                clearable
            >
              <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
            >
              <el-option
                  v-for="item in dictionaries.sale_status"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="fetchData('search')">查询</el-button>
            <el-button
                type="primary"
                plain
                @click="fetchData('reset')"
            >重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="content">
      <h3>列表数据</h3>
      <div class="btn-list">
        <div class="item">
        <el-button plain
            :type=" currentStatus === groupByStatus.totalCount ? 'primary' : 'info' "
            @click="onChangeList(groupByStatus.totalCount)"
        >全部({{ countGroupByStatus.totalCount }})</el-button>
        <el-button plain
            :type=" currentStatus === groupByStatus.onSaleCount ? 'primary' : 'info'"
            @click="onChangeList(groupByStatus.onSaleCount)"
        >上架中商品({{ countGroupByStatus.onSaleCount }})</el-button>
        <el-button plain
            :type=" currentStatus === groupByStatus.offSaleCount ? 'primary' : 'info' "
            @click="onChangeList(groupByStatus.offSaleCount)"
        >已下架商品({{ countGroupByStatus.offSaleCount }})</el-button>
        </div>
        <div class="item">
          <el-button
           v-if="parArray.indexOf('putOnCode') != -1"
              @click="operationStatus('up')"
              :disabled = "currentStatus === groupByStatus.onSaleCount ? true : false"
          >批量上架</el-button>
          <el-button style="color: #2D7EDF;"
           v-if="parArray.indexOf('putOffCode') != -1"
              @click="operationStatus('down')"
              :disabled = "currentStatus === groupByStatus.offSaleCount ? true : false"
          >批量下架</el-button>
          <el-button type="primary" @click="onGoodsExport()" class="goods-export" :loading="GoodsExportLoading">导出商品</el-button>
          <el-button type="primary" @click="toOtherPages('goodsCategoryEdit' )" v-if="parArray.indexOf('goodsadd_xzsp') != -1">新增</el-button>

        </div>
      </div>
      <div id="base-list" >
        <lb-table
			v-loading="loading"
      v-horizontal-scroll='"always"'
            :column="columns"
            :data="list"
            pagination
            :total="page.totalNum"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[5, 10, 20, 30, 50]"
            :current-page.sync="page.currentPage"
            :page-size="page.pageSize"
            @selection-change="onMultipleSelection"
            @size-change="handleSizeChange"
            @p-current-change="handleCurrentChange"
        >
        </lb-table>
      </div>
<!--      <base-list :baseColumns="columns" :baseList="list" :searchObj="search" v-on:onMultipleSelection="onMultipleSelection" ref="baseList"></base-list>-->
    </div>
    <!--========================== el-dialog =================================-->
    <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :width="dialog.width"
        :append-to-body="true"
    >
      <template v-if="dialog.type === 'skuList'">
        <el-table
            :data="dialog.list"
            style="width: 100%">
          <el-table-column
              prop="skuNo"
              label="SKU编码"
              width="150">
          </el-table-column>
          <el-table-column
              prop="name"
              label="商品规格">
            <template slot-scope="scope">
              <span v-if="scope.row.secondGoodsSpecItemContent">{{scope.row.firstGoodsSpecItemContent}} + {{scope.row.secondGoodsSpecItemContent}}</span>
              <span v-else-if="scope.row.thirdGoodsSpecItemContent">{{scope.row.firstGoodsSpecItemContent}} + {{scope.row.secondGoodsSpecItemContent}} + {{scope.row.thirdGoodsSpecItemContent}}</span>
              <span v-else>{{scope.row.firstGoodsSpecItemContent}}</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="marketPrice"
              label="市场价">
          </el-table-column>
          <el-table-column
              prop="retailPrice"
              label="零售价">
          </el-table-column>
          <el-table-column
              prop="stock"
              label="库存">
          </el-table-column>
          <el-table-column
              label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="onCopySku(scope.row.skuNo)">复制</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-dialog>
  </div>
</template>
<script>
// import { getClientWidth } from "../../../utils/index.js";
import LbTable from '../../components/lb-table/lb-table'
import BaseList from './components/BaseList.vue'
import breadcrumbTop from '../../components/breadcrumb.vue'
export default {
  components: {
    LbTable,
    breadcrumbTop
    // BaseList
  },
  data () {
    return {
      GoodsExportLoading: false,
      dataList: {
        list: [
          { title: '商品管理', path: '', type: '0' },
          { title: '商品列表', path: '', type: '1' }
        ]
      },
      searchForm: {
        name: '', // 	否 	string 	商品名称
        goodsNo: '', // 	否 	string 	商品编号
        categoryId: '', // 	否 	int 	类目id（数据来源：接口 - /order/comm/commodityCategory/commList）
        brandId: '', // 	否 	int 	品牌id（数据来源：接口 - /order/comm/brand/list?pageNo=1&pageSize=999）
        goodsType: '', // 	否 	int 	类型（1：普通商品；2：虚拟商品；3：赠品；字典：goods_type）
        status: '', // 	否 	int 	状态（字典：sale_status）
        orderBy: '', // 	否 	int 	排序（0价格；1可用库存；2总销量）
        orderByType: '' // 	否 	int 	排序方式（0正序；1倒序）
      },
      currentStatus: 100, // 当前列表状态
      groupByStatus: { // 数据切换
        totalCount: 100, // 全部
        onSaleCount: 200, // 上架中商品
        offSaleCount: 300 // 已下架商品
      },
      countGroupByStatus: { // 商品列表数量统计
        totalCount: 100, // 总数
        onSaleCount: 200, // 上架数量
        offSaleCount: 300 // 下架数量
      },
      // 数据列表
      list: [],
	  loading:false,
      categoryList: [], // 目类列表
      brandList: [], // 品牌
      columns: [
        { type: 'selection', minWidth: '80', fixed: 'left' },
        { label: '商品编号', prop: 'goodsNo', minWidth: '120' },
        {
          label: '商品图片',
          minWidth: '200',
          render: (h, scope) => {
            return (
              <div>
                <el-image src={scope.row.mainImageArr[0]} preview-src-list={scope.row.mainImageArr} lazy></el-image>
              </div>
            )
          }
        },
        { label: '商品名称', prop: 'name', minWidth: '220' },
        { label: '商品品牌', prop: 'brandName', minWidth: '120' },
        { label: '商品类目', prop: 'categoryName', minWidth: '120' },
        { label: '商品类型', prop: 'goodsType', minWidth: '120' },
        { label: '价格', prop: 'marketPrice', minWidth: '120', sortable: true },
        { label: '可用库存', prop: 'stock', minWidth: '120', sortable: true },
        { label: '总销量', prop: 'soldNum', minWidth: '120', sortable: true },
        {
          label: '状态',
          minWidth: '100',
          render: (h, scope) => {
            return (
              <div>
                <p class={scope.row.status === 1 ? 'success' : 'danger'}>{scope.row.statusLabel}</p>
              </div>
            )
          }
        },
        { label: '创建时间', prop: 'createdTime', minWidth: '200' },
        { label: '最后编辑时间', prop: 'updatedTime', minWidth: '200', sortable: true },
        {
          label: '操作',
          minWidth: '180',
          fixed: 'right',
          render: (h, scope) => {
            return (
              <div>
                <el-link size='mini' type='primary' onClick={() => { this.operationStatus(scope.row.status === 1 ? 'down' : 'up', scope.row) }} class={this.parArray.indexOf('putOnCode') != -1 ? 'info' : 'hide-content'}>{scope.row.status === 1 ? '下架' : '上架'}</el-link>
                <el-link size='mini' type='primary' onClick={() => { this.toOtherPages('goodsEdit', scope.row.id, 'edit') }} class={this.parArray.indexOf('goods_eidt_ckbj') != -1 ? 'info' : 'hide-content'}>查看/编辑</el-link>
                <el-link size='mini' type='primary' onClick={() => { this.getGoodCopySku('skuList', scope.row) }}>复制SKU编码</el-link>
                <el-link size='mini' type='danger' onClick={() => { this.onGoodsDelete(scope.row, scope.$index) }} class={this.parArray.indexOf('delete_goods_sc') != -1 ? 'info' : 'hide-content'}>删除</el-link>
              </div>
            )
          }
        }],
      page: { pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1, status: '' },
      dialog: { visible: false, title: '编辑', type: '', row: {}, list: [], batch: false },
      dictionaries: { // 字典数据
        sale_status: [], // 状态
        goods_type: [] // 商品类型
      },
      selectionGoods: [], // 选 中 商品
      parArray: [] // 按钮权限
    }
  },
  mounted () {

  },
  created () {
    this.fetchData()
    this.getCategoryList() // 获取 目类 列表
    this.getBrandList() // 获取 品牌 列表
    // 权限设定判断
    this.limits = JSON.parse(sessionStorage.getItem('limit'))
    const params = this.limits.buttonTreeDto.filter(
      (item) => item.menuCode === 'goodsList'
    )
    params[0].buttonList.forEach((item) => {
      this.parArray.push(item.code)
    })
    // 获取字典值
    for (const type in this.dictionaries) { this.getDictionaries(type) }
  },
  /*
  watch: {
    screenWidth(val) {
      this.screenWidth = val;
      console.log("this.screenWidth",this.screenWidth)
      this.windowOnresize()
    }
  },
  */
  methods: {
    fetchData (type) {
		this.loading = true;
      if (type == 'reset') {
        this.$refs['searchForm'].resetFields()
        this.page.pageNo = 1
        this.page.pageSize = 10
      }
      let params = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        status: this.page.status
      }
      if (type == 'search') { params.pageNo = 1 }
      const searchForm = this.searchForm
      params = Object.assign(params, searchForm)
      params.categoryId = searchForm.categoryId[searchForm.categoryId.length - 1]
      // 去除字符串 前后 空格
      for (const item in params) { if (typeof params[item] === 'string') { params[item] = params[item].trim() } }
      const upIndex = this.dictionaries.sale_status.findIndex(e => { return e.dictName.indexOf('上') > -1 })
      const downIndex = this.dictionaries.sale_status.findIndex(e => { return e.dictName.indexOf('下') > -1 })
      if (type === 'up' || this.currentStatus === this.groupByStatus.onSaleCount) {
        params.status = Number(this.dictionaries.sale_status[upIndex].dictId)
        this.page.status = params.status
      }
      if (type === 'down' || this.currentStatus === this.groupByStatus.offSaleCount) {
        params.status = Number(this.dictionaries.sale_status[downIndex].dictId)
        this.page.status = params.status
      }
      console.log(params)
      this.$api.goodsPageList(params).then((res) => {
        if (res.code === 0) {
          res.data.list.forEach(e => {
            // if (e.mainImage && e.mainImage.indexOf('http://fenxiao.muruji.com/') !== 0) { e.mainImage = this.ImgHttps + e.mainImage }
            /*
            if (e.mainImage && e.mainImage.indexOf('http://fenxiao.muruji.com/') !== 0) {
              e.mainImage = this.ImgHttps + e.mainImage
            } else {
              // e.mainImage = e.mainImage.replace('http://', 'https://')
              console.log(e.mainImage)
            }
            */
            e.marketPrice = Number(e.marketPrice)
            e.stock = Number(e.stock)
            e.soldNum = Number(e.soldNum)
            e.mainImageArr = []
            e.mainImageArr.push(e.mainImage)
            e.skuList.forEach(it => {
              it.skuNo = e.goodsNo + it.skuNo
            })
          })
          this.list = res.data.list
          this.page.totalNum = res.data.totalNum
        } else {
          console.log('goodsPageList - 失败', type)
        }
		this.loading = false;
        this.getCountGroupByStatus()// 获取商品列表数量统计
      }).catch((err) => {
		  this.loading = false;
        console.log(err)
      })
    },
    handleCurrentChange (currentChange) {
      this.page.pageNo = currentChange
      this.fetchData()
    },
    handleSizeChange (sizeChange) {
      this.page.pageSize = sizeChange
      this.fetchData()
    },
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
        (item) => item.menuCode === 'companyCode'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })
    },
    // 获取字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取商品列表数量统计
    getCountGroupByStatus () {
      const params = {}
      this.$api.countGroupByStatus(params).then((res) => {
        this.countGroupByStatus = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取类目列表
    getCategoryList () {
      const params = {}
      this.$api.categoryList(params).then((res) => {
        this.categoryList = res.data.list
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取 品牌 列表
    getBrandList () {
      const params = { pageNo: 1, pageSize: 999 }
      this.$api.brandCommList(params).then((res) => {
        this.brandList = res.data.list
      }).catch((err) => {
        console.log(err)
      })
    },
    // 搜索 选择 类目
    onChangeCategory (val) {
      // this.search.classId = val[val.length -1]
      // console.log(val, this.search.classId)
    },
    // 切换当前列表
    onChangeList (state) {
      this.page = { pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 }
      this.currentStatus = state
      // if ( this.currentStatus === this.assignStatus.all) {}
      if (this.currentStatus === this.groupByStatus.totalCount) { this.fetchData('all') }
      if (this.currentStatus === this.groupByStatus.onSaleCount) { this.fetchData('up') }
      if (this.currentStatus === this.groupByStatus.offSaleCount) { this.fetchData('down') }
    },
    // 多选
    onMultipleSelection (val) {
      this.selectionGoods = val
    },
    // 上架、下架
    operationStatus (type, row) {
      console.log(type, row)
      let msg = type === 'up' ? `是否上架商品, 是否继续?` : `是否下架商品, 是否继续?`
      const params = { ids: [] }
      const selectionId = []
      const selectionGoods = this.selectionGoods
      selectionGoods.forEach(e => { selectionId.push(e.id) })
      if (row) {
        params.ids.push(row.id)
        msg = type === 'up' ? `是否上架【${row.name}】, 是否继续?` : `是否下架【${row.name}】, 是否继续?`
      } else { params.ids = selectionId }
      // console.log(selectionId.length, type, selectionId)

      if (params.ids.length === 0) { return this.$message({ type: 'error', message: '需要选择商品!' }) }

      if (type === 'up') {
        const findObj = selectionGoods.find(e => { return e.status === 1 })
        if (findObj) { return this.$message({ type: 'error', message: '已有商品上架!' }) }
      }
      if (type === 'down') {
        const findObj = selectionGoods.find(e => { return e.status === 0 })
        if (findObj) { return this.$message({ type: 'error', message: '已有商品下架!' }) }
      }

      let operationFun
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        switch (type) {
          case 'up':
            operationFun = this.$api.goodsPutOn
            // this.column = columnConsumption
            break
            // 分配记录
          case 'down':
            operationFun = this.$api.goodsPutOff
            break
            // default:
        }
        operationFun(params).then((res) => {
          this.fetchData()
          this.$message({ type: 'success', message: '操作成功!' })
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 删除商品
    onGoodsDelete (row) {
      const msg = `此操作将删除【${row.name}】, 是否继续?`
      this.$confirm(msg, '提示', {
        title: '删除商品',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const params = { id: row.id }
        this.$api.goodsDelete(params).then((res) => {
          this.fetchData()
          this.$message({ type: 'success', message: '操作成功!' })
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    toOtherPages (name, parameter, type) {
      this.$router.push({
        name,
        query: { id: parameter, type }
      })
    },
    // 获取 商品 KSU
    getGoodCopySku (skuList, row) {
      this.setCloseOrder = ''
      this.dialog.visible = true
      this.dialog.title = '复制SKU码'
      this.dialog.width = '640px'
      this.dialog.type = 'skuList'
      this.dialog.list = row.skuList
      // this.cancelOrderId = row.orderId
      // console.log('getGoodCopySku', this.dialog.list)
    },
    // 复制 KSU
    onCopySku (info) {
      // console.log('onCopySku', info)
      const t = this
      this.$copyText(info).then(
        function (e) {
          t.$message({
            type: 'success',
            message: '复制成功'
          })
        },
        function (e) {
          t.$message({
            type: 'warning',
            message: '复制失败'
          })
        }
      )
    },
    // 商品导出
    onGoodsExport () {
      this.GoodsExportLoading = true
      let params = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        status: this.currentTab
      }
      params = Object.assign(params, this.searchForm)
      // 类目id
      const tempCategoryIdArr = [].concat(params.categoryId)
      if (tempCategoryIdArr && tempCategoryIdArr.length !== 0) {
        params.categoryId = tempCategoryIdArr[tempCategoryIdArr.length - 1]
      }
      for (const item in params) {
        if (typeof params[item] === 'string') {
          params[item] = params[item].trim()
          if (params[item] === '') { delete params[item] }
        }
      }
      this.$api.goodsExport(params).then((res) => {
        this.GoodsExportLoading = false
        this.downloadlink(res.data)
        this.$message.success('操作成功！')
      }).catch((err) => {
        this.GoodsExportLoading = false
        console.log(err)
      })
    }
  }
}
</script>
<style scoped lang="scss">

/deep/.hide-content{display: none!important;}
//删除全页面按钮边框
.el-button{ border: none;}
// 按钮
.btn-list{
  margin-bottom: 22px;
  display: flex;
  .item{
    flex: 1;
    &:last-child{
      text-align: right;

      .el-button{
        width: 120px;
        color: #2D7EDF;
        border: 1px solid #2D7EDF;
        &:last-child, .goods-export{
          color: #ffffff;
          border: 1px solid #409EFF;
        }
      }
      .goods-export{
        color: #ffffff;
        border: 1px solid #409EFF;
      }
    }
    .el-button{
      height: 36px;
      line-height: 36px;
      padding-top: 0;
      padding-bottom: 0;
    }
    .is-disabled{
      background-color: #f4f4f5!important;
      border: 1px solid #d3d4d6!important;
      color: #909399!important;
    }
  }
}
.search-form{
  display: flex;
  flex-wrap: wrap;
  .el-form-item{
    /deep/ .el-form-item__label{
      width: 82px;
      text-align: right;
      vertical-align: middle;
      float: left;
      box-sizing: border-box;
    }
    /deep/ .el-form-item__content{
      display: block;
      margin-left: 82px;
      .el-cascader, .el-select{
        width: 100%;
      }
    }
  }
}
/deep/.el-scrollbar{
  height:10px;
}
/deep/.el-scrollbar__bar.is-horizontal{
  height: 9px;

}

:deep(#base-list .lb-table .el-table .el-table__body .el-table__row .el-table__cell:last-child .cell div){
  display: inline-block;
  a{ margin: 0 5px; }
}
</style>
